﻿/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "WifiBurnDlg.h"
#include <QMessageBox>
#include <QSettings>
#include <QFileDialog>
#include <QTimer>
#include <QTranslator>
#include <QScrollBar>
#include <QWidgetAction>
#include "BurnToolCommon/Global.h"
#include "BurnCtrl/BurnCtrlFaction.h"
#include "DataConvertor.h"
#include "DiaglogComSetting.h"
#include "SecureLink/Channel.h"

namespace BurnDlg {

namespace {
    const int COLUMN_WIDTH_SIZE_20 = 20;
    const int COLUMN_WIDTH_SIZE_100 = 100;
    const int COLUMN_WIDTH_SIZE_200 = 200;
    const int COLUMN_WIDTH_SIZE_300 = 300;
    const int COLUMN_WIDTH_SIZE_500 = 500;
    const int COLUMN_MINIMUM_HEIGHT_SIZE_192 = 192;
    const int COLUMN_MINIMUM_HEIGHT_SIZE_400 = 400;
    const int CONFIGTIMER_INTERVAL_100 = 100;
    const int MAX_BLOCK_COUNT_1000 = 1000;
    const int NUMBER_ONE_HUNDRED = 100;
    const int NUMBER_TWO_HUNDRED = 200;
    const int YMODEM_MAX_PACKAGE_SIZE = 40960;
    const int ADDR_AT = 5;
    const int SIZE_AT = 6;
    const char* const ERASE_CONFIG = "erase_config";
    const char* const IS_ERASE = "isErase";
    const QString BURN_INTERVAL_2MS = "2";
    const QString BURN_INTERVAL_10MS = "10";
}

WifiBurnDlg::WifiBurnDlg(ChipType chipType, QWidget *pParent)
    : BurnDlg(pParent),
      ui(new Ui::WifiBurnDlg),
      actImportConfig(new QAction(stringClass.GetActionImportConfig())),
      actSaveConfig(new QAction(stringClass.GetActionSaveConfig())),
      actSettings(new QAction(stringClass.GetActionSettings())),
      actChangeChip(new QAction(stringClass.GetChangeChip())),
      actAbout(new QAction(stringClass.GetAbout())),
      comboBoxBurnInterval(nullptr),
      alwaysClear(true),
      isMultipleBurnOpen(false),
      isAutoDisconnect(false),
      eraseMode(0),
      isInserting(false),
      multipleBurnDlg(nullptr),
      configTimer(nullptr)
{
    BurnDlg::chipType = chipType;
    efuseStartBit.clear();
    efuseBitWidth.clear();
    radiobtngrpBoot = 0;
    isInserting = false;
    if (ui != nullptr && actEnglish != nullptr && actChinese != nullptr &&
        actImportConfig != nullptr && actSaveConfig != nullptr && actSettings != nullptr && actChangeChip != nullptr &&
        actAbout != nullptr) {
        ui->setupUi(this);
        QMenu *menuBurnInterval = new QMenu(stringClass.GetBurnInterval());
        if (menuBurnInterval != nullptr) {
            comboBoxBurnInterval = new QComboBox();
            comboBoxBurnInterval->addItem(BURN_INTERVAL_2MS);
            comboBoxBurnInterval->addItem(BURN_INTERVAL_10MS);
            comboBoxBurnInterval->setCurrentText(BURN_INTERVAL_10MS);
            comboBoxBurnInterval->setEditable(true);
            comboBoxBurnInterval->lineEdit()->setValidator(new QIntValidator(this));
            comboBoxBurnInterval->setMinimumWidth(60); // 最小宽度为 60
            QWidgetAction* qWidgetAction = new QWidgetAction(menuBurnInterval);
            qWidgetAction->setDefaultWidget(comboBoxBurnInterval);
            menuBurnInterval->addAction(qWidgetAction);
        }

        ui->menuSetting->addAction(actSettings);
        ui->menuSetting->addMenu(menuBurnInterval);
        ui->menuSetting->addAction(actImportConfig);
        ui->menuSetting->addAction(actSaveConfig);
        ui->menuSetting->addMenu(menuWifiLanguage);
        ui->menuOption->addAction(actChangeChip);
        binModel = new BinFileModel();
        if (binModel != nullptr) {
            ui->tableView->setModel(binModel);
        }
        ui->menuHelp->addAction(actAbout);
        InitializeInterfaceControls();
        ui->lineEditSeleteFile->setFocusPolicy(Qt::NoFocus);
    }
    InitGetSettingCfg();
    InitMenus();
}

void WifiBurnDlg::InitMenus()
{
    this->tableViewMenu = new QMenu(this);
    addAdrAction = new QAction(tr("Sync address..."));
    if (addAdrAction != nullptr) {
        this->tableViewMenu->addAction(addAdrAction);

        connect(addAdrAction, &QAction::triggered, this, &WifiBurnDlg::SlotAddAdrAction);
    }
    QAction *createNewFileAction = new QAction(stringClass.GetCreateNewFile());
    if (createNewFileAction != nullptr) {
        this->tableViewMenu->addAction(createNewFileAction);
        connect(createNewFileAction, &QAction::triggered, this, &WifiBurnDlg::SlotCreateNewFwpkgFile);
    }
    QAction *saveSpiltFileAction = new QAction(stringClass.GetSaveSplitFile());
    if (saveSpiltFileAction != nullptr) {
        this->tableViewMenu->addAction(saveSpiltFileAction);
        connect(saveSpiltFileAction, &QAction::triggered, this, &WifiBurnDlg::SlotSaveSpiltFwpkgFile);
    }
    QRegExp rx("^0x[0-9a-f]{1,8}|^[0-9]{1,8}");
    QRegExpValidator *pReg = new QRegExpValidator(rx);
    if (ui != nullptr) {
        ui->lineEditAddr->setValidator(pReg);
        ui->lineEditSize->setValidator(pReg);
    }
}

void WifiBurnDlg::SlotCreateNewFwpkgFile()
{
    CreateNewFwpkgFile(ui->lineEditSeleteFile->text());
}

void WifiBurnDlg::SlotSaveSpiltFwpkgFile()
{
    SaveSpiltFwpkgFile(ui->lineEditSeleteFile->text());
}

void WifiBurnDlg::SlotAddAdrAction() const
{
    if (ui == nullptr || !IsSelectionRows()) {
        return;
    }

    QModelIndex indexChoose = ui->tableView->selectionModel()->currentIndex();
    int addRow = indexChoose.row();
    QModelIndex indexAddr = ui->tableView->model()->index(addRow, ADDR_AT);
    QModelIndex indexSize = ui->tableView->model()->index(addRow, SIZE_AT);
    QString addr = ui->tableView->model()->data(indexAddr).toString();
    QString size = ui->tableView->model()->data(indexSize).toString();

    ui->lineEditAddr->setText(addr);
    ui->lineEditSize->setText(size);
}

void WifiBurnDlg::contextMenuEvent(QContextMenuEvent *event)
{
    Q_UNUSED(event);
    if (!IsSelectionRows()) {
        return;
    }
    // 菜单出现的位置为当前鼠标的位置
    this->tableViewMenu->exec(QCursor::pos());
}


bool WifiBurnDlg::IsSelectionRows() const
{
    if (ui == nullptr) {
        return false;
    }
    QModelIndexList list = ui->tableView->selectionModel()->selectedIndexes();
    QModelIndex index = ui->tableView->selectionModel()->currentIndex();
    if (list.isEmpty() || !index.isValid()) {
        return false;
    }
    return true;
}

void WifiBurnDlg::InitializeInterfaceControls()
{
    this->WifiBurnDlg::InitBurnCtrl();
    if (ui == nullptr || burnCtrl == nullptr) {
        return;
    }
    // 界面控件z
    if (Global::currentChipTypeId == ChipType::WIFIURANUS) {
        ui->btnCom->setEnabled(true);
    } else {
        ui->btnCom->setEnabled(false);
    }
    ui->comboBoxCom->setEditable(true);
    ui->comBoxEfuse->setEditable(true);
    ui->comBoxEarseMode->setEditable(true);
    ui->comBoxEarseMode->addItem(stringClass.GetNormal());
    ui->comBoxEarseMode->addItem(stringClass.GetEraseAll());
    ui->comBoxEarseMode->addItem(stringClass.GetNoErase());
    IsEarseModeHide();
    SlotCbnSetfocusComboCom();
    ui->textEditReceive->setReadOnly(true);
    ui->textEditReceive->document()->setMaximumBlockCount(MAX_BLOCK_COUNT_1000);
    ui->textEditReceive->setTextInteractionFlags(Qt::TextSelectableByMouse);
    ui->progressBarReceive->setRange(0, SHRT_MAX);
    ui->progressBarReceive->setValue(0);
    burnCtrl->StartWiteMonitoring();
    InitSettingsConnect();
    InitButtonConnect();
    InitBurnCtrlConnect();
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setDefaultDropAction(Qt::MoveAction);
    ui->tableView->setDragDropMode(QAbstractItemView::InternalMove);
    ui->checkBoxAutoDisconnect->setCheckState(isAutoDisconnect ? Qt::Checked : Qt::Unchecked);
    ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_CHECK, COLUMN_WIDTH_SIZE_20);
    ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_ADD, COLUMN_WIDTH_SIZE_20);
    ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_DELETE, COLUMN_WIDTH_SIZE_20);
    ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_NAME, COLUMN_WIDTH_SIZE_100);
    ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_PAHT, COLUMN_WIDTH_SIZE_200);
    ui->tableView->setMinimumHeight(COLUMN_MINIMUM_HEIGHT_SIZE_192);
    ui->tableView->horizontalHeader()->setSectionResizeMode(TABLEVIEW_COLUMN_CHECK, QHeaderView::Fixed);
    ui->tableView->horizontalHeader()->setSectionResizeMode(TABLEVIEW_COLUMN_ADD, QHeaderView::Fixed);
    ui->tableView->horizontalHeader()->setSectionResizeMode(TABLEVIEW_COLUMN_DELETE, QHeaderView::Fixed);
    InitializeInterfaceControlsAdd();
    if (Global::currentChipTypeId == ChipType::TCPWS63) {
        ui->btnCom->setText("TCP");
        ui->comboBoxCom->clear();
        ui->comboBoxCom->setEditText("0.0.0.0:10001");
        portType = Base::TCP_PORT;
        ui->btnMultipleBurn->setEnabled(false);
    }
}

void WifiBurnDlg::InitializeInterfaceControlsAdd()
{
    configTimer = new QTimer(this);
    if (configTimer != nullptr) {
        connect(configTimer, &QTimer::timeout, this, &WifiBurnDlg::SlotConfigTimerTimeOut);
        configTimer->start(CONFIGTIMER_INTERVAL_100);
    }
    connect(ui->comboBoxCom, &ComboBoxCom::Clicked, this, &WifiBurnDlg::SlotCbnSetfocusComboCom);
    connect(ui->checkBoxAutoBurn, &QCheckBox::clicked, this, &WifiBurnDlg::SlotAutoBurnClick);
    connect(ui->checkBoxAutoBurn, &QCheckBox::stateChanged, this, &WifiBurnDlg::SlotCheckAutoBurnStateChanged);
    connect(ui->checkBoxAutoDisconnect, &QCheckBox::stateChanged, this,
            &WifiBurnDlg::SlotCheckAutoDisconnectStateChanged);
    connect(ui->comBoxEarseMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SlotEarseModeCurrentIndexChanged(int)));
    if (binModel != nullptr) {
        connect(binModel, &BinFileModel::dataChanged, this, &WifiBurnDlg::SlotLvnItemchangedListBinPath);
        connect(binModel, &QAbstractItemModel::modelReset, this, &WifiBurnDlg::SlotmodelReset);
    }
}

void WifiBurnDlg::IsEarseModeHide() const
{
    if (ui == nullptr) {
        return;
    }
    QString fileName = QCoreApplication::applicationDirPath() + "\\configure";
    QSettings cfg(fileName + "\\config_setting.ini", QSettings::IniFormat);
    int isEraseHide = cfg.value(QString(ERASE_CONFIG) + "/" + QString(IS_ERASE)).toInt();
    if (isEraseHide == 0) {
        ui->comBoxEarseMode->setHidden(true);
    }
}

WifiBurnDlg::~WifiBurnDlg()
{
    if (ui != nullptr) {
        delete ui;
        ui = nullptr;
    }
    if (setting != nullptr) {
        delete setting;
        setting = nullptr;
    }

    if (multipleBurnDlg != nullptr) {
        delete multipleBurnDlg;
        multipleBurnDlg = nullptr;
    }

    if (comboBoxBurnInterval != nullptr) {
        delete comboBoxBurnInterval;
        comboBoxBurnInterval = nullptr;
    }

    if (actImportConfig != nullptr) {
        delete actImportConfig;
        actImportConfig = nullptr;
    }

    if (actSaveConfig != nullptr) {
        delete actSaveConfig;
        actSaveConfig = nullptr;
    }

    if (actSettings != nullptr) {
        delete actSettings;
        actSettings = nullptr;
    }

    if (actEnglish != nullptr) {
        delete actEnglish;
        actEnglish = nullptr;
    }

    WifiBurnDlgDelete();
}

void WifiBurnDlg::WifiBurnDlgDelete()
{
    if (actChinese != nullptr) {
        delete actChinese;
        actChinese = nullptr;
    }

    if (actChangeChip != nullptr) {
        delete actChangeChip;
        actChangeChip = nullptr;
    }

    if (actAbout != nullptr) {
        delete actAbout;
        actAbout = nullptr;
    }

    if (addAdrAction != nullptr) {
        delete addAdrAction;
        addAdrAction = nullptr;
    }

    if (binModel != nullptr) {
        delete binModel;
        binModel = nullptr;
    }
    if (encryptBuffer.bufferData != nullptr) {
        delete [] encryptBuffer.bufferData;
        encryptBuffer.bufferData = nullptr;
    }
    encryptBuffer.bufferLen = 0;

    if (configTimer != nullptr) {
        configTimer->stop();
        delete configTimer;
        configTimer = nullptr;
    }
}

void WifiBurnDlg::SlotConfigTimerTimeOut()
{
    if (configTimer == nullptr) {
        return;
    }
    configTimer->stop();
    delete configTimer;
    configTimer = nullptr;
    QString path = DataConvertor::GetBurnToolConfigPathNew();
    QFile file(path);
    if (file.exists()) {
        if (QMessageBox::information(this, tr("BurnTool"), stringClass.GetLoadExistingConfig(),
                                     stringClass.GetYes(), stringClass.GetNo()) != 0) {
            return;
        }
    } else {
        return;
    }
    LoadDlgConfig();
}

void WifiBurnDlg::InitBurnCtrlConnect()
{
    if (burnCtrl == nullptr) {
        return;
    }
    connect(burnCtrl, &BurnCtrl::SignalInsertPlainText, this, &WifiBurnDlg::SlotInsertPlainText);
    connect(burnCtrl, &BurnCtrl::SignalClearPlainText, this, &WifiBurnDlg::SlotClearPlainText);
    connect(burnCtrl, &BurnCtrl::SignalReplacePlainText, this, &WifiBurnDlg::SlotReplacePlainText);
    connect(burnCtrl, &BurnCtrl::SignalSwitchDfu, this, &WifiBurnDlg::SlotSwitchDfu);
    connect(burnCtrl, &BurnCtrl::SignalAutoDisconnect, this, &WifiBurnDlg::SlotAutoDisconnect);
    connect(burnCtrl, &BurnCtrl::SignalMergeCurrentCharFormat, this, &WifiBurnDlg::SlotMergeCurrentCharFormat);
    connect(burnCtrl, &BurnCtrl::SignalSetProgressValue, this, &WifiBurnDlg::SlotSetProgressValue);
    connect(burnCtrl, &BurnCtrl::SignalSetProgressRange, this, &WifiBurnDlg::SlotSetProgressRange);
}

void WifiBurnDlg::InitSettingsConnect()
{
    if (ui != nullptr && comboBoxBurnInterval != nullptr && actEnglish != nullptr && actChinese != nullptr &&
        actImportConfig != nullptr && actSaveConfig != nullptr && actSettings != nullptr && actChangeChip != nullptr &&
        actAbout != nullptr) {
        connect(comboBoxBurnInterval->lineEdit(), &QLineEdit::editingFinished, this, &WifiBurnDlg::SlotSetBurninterval);
        connect(actSettings, &QAction::triggered, this, &WifiBurnDlg::SlotShowMenuSettings);
        connect(actSaveConfig, &QAction::triggered, this, &WifiBurnDlg::SlotSaveConfig);
        connect(actImportConfig, &QAction::triggered, this, &WifiBurnDlg::SlotImportConfig);
        connect(actChangeChip, &QAction::triggered, this, &WifiBurnDlg::SlotShowChangeChip);
        connect(ui->menuOption, &QMenu::aboutToShow, this, &WifiBurnDlg::SlotActionShow);
        // help
        connect(actAbout, &QAction::triggered, this, &WifiBurnDlg::SlotShowAbout);
        connect(ui->menuSetting, &QMenu::aboutToShow, this, &WifiBurnDlg::SlotActionShow);
    }
}

void WifiBurnDlg::InitButtonConnect()
{
    if (ui == nullptr) {
        return;
    }
    connect(ui->btnSelectFile, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedButtonSelectfile);
    connect(ui->btnCom, &QPushButton::clicked, this, &WifiBurnDlg::SlotButtonClickedCom);
    connect(ui->btnConnect, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedButtonConn);
    connect(ui->btnImportEfuse, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedButtonImportEfuseConfig);
    connect(ui->btnReadEfuse, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedButtonReadEfuse);
    connect(ui->btnSendFile, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedButtonStartburn);
    connect(ui->btnSelectTarget, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedSelectTarget);
    connect(ui->btnReset, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedReset);
    connect(ui->btnEraseAll, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedEraseAll);
    connect(ui->btnExport, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedExport);
    connect(ui->btnMultipleBurn, &QPushButton::clicked, this, &WifiBurnDlg::SlotBnClickedMultipleBurn);
    connect(ui->tableView->horizontalHeader(), &QHeaderView::sectionClicked, this,
            &WifiBurnDlg::SlotBnClickedTableHeader);
    connect(ui->tableView, &QTableView::clicked, this, &WifiBurnDlg::SlotBnClickedTableView);
    connect(ui->tableView, &QTableView::doubleClicked, this, &WifiBurnDlg::SlotBnDoubleClickedTableView);
}

void WifiBurnDlg::SlotShowMenuSettings()
{
    if (burnCtrl == nullptr) {
        return;
    }

    if (radiobtngrpBoot == BOOT_LOADER) {
        BurnDlg::SlotShowMenuSettings();
        return;
    }

    if (setting == nullptr) {
        setting = new DiaglogComSetting(this);
    }
    int wifiBaudRate;
    int wifiDataBits;
    int wifiStopBits;
    QSerialPort::Parity wifiParity;
    int wifiFlowCtrl;
    GetComSettingFromGloble(wifiBaudRate, wifiDataBits, wifiStopBits, wifiParity, wifiFlowCtrl);
    if (setting != nullptr) {
        setting->SetComConfig(wifiBaudRate, wifiDataBits, wifiStopBits, wifiParity, wifiFlowCtrl);
        setting->SetMultipleBurnParam(burnCtrl->GetMultiBurnTotalNum(), burnCtrl->GetMultiBurnNumPerLine(),
                                      burnCtrl->GetMultiBurnIndenpendentBurn(), burnCtrl->GetMultiBurnReopenCom());
        setting->SetIsResetAfterSuccess(burnCtrl->GetIsResetAfterSuccess());
        setting->SetIsSwitchAfterLoader(burnCtrl->GetIsSwitchAfterLoader());
        setting->SetYModemPackageSize(burnCtrl->GetYModemEachPackageSize());
        setting->SetForceRead(burnCtrl->GetForceReadFlag());
        setting->SetForceReadTimr(burnCtrl->GetForceReadTime());
        setting->Set4GCat1TotalAndLineNum(Global::currentChipTypeId);
        setting->SetCurrentValue();
        connect(setting, &DiaglogComSetting::SignalSettingSuccess, this, &WifiBurnDlg::SlotSettingSuccess);
        if (portType == Base::TCP_PORT) {
            setting->ComSettingEnable(false);
        }
        setting->show();
    }
}

void WifiBurnDlg::SlotSettingSuccess()
{
    if (burnCtrl == nullptr) {
        return;
    }
    int baud;
    int databits;
    int stopbits;
    QSerialPort::Parity parityWifi;
    int flowctrl;
    if (setting != nullptr) {
        setting->GetComConfig(baud, databits, stopbits, parityWifi, flowctrl);
        SetComSettingToGloble(baud, databits, stopbits, parityWifi, flowctrl);
        burnCtrl->SetForceReadFlag(setting->GetForceRead());
        burnCtrl->SetYModemEachPackageSize(setting->GetYModemPackageSize());
        burnCtrl->SetForceReadTime(setting->GetForceReadTime());
        unsigned int totalWifiNum;
        unsigned int numPerLine;
        bool indenpendent = false;
        bool reopenCom = false;
        bool resetAfterSuccess = false;
        bool switchAfterLoader = false;
        setting->GetMultipleBurnParam(totalWifiNum, numPerLine, indenpendent, reopenCom);
        setting->GetIsResetAfterSuccess(resetAfterSuccess);
        setting->GetIsSwitchAfterLoader(switchAfterLoader);
        burnCtrl->SetMultiBurnTotalNum(totalWifiNum);
        burnCtrl->SetMultiBurnNumPerLine(numPerLine);
        burnCtrl->SetMultiBurnIndenpendentBurn(indenpendent);
        burnCtrl->SetReopenComFlag(reopenCom);
        burnCtrl->SetIsResetAfterSuccess(resetAfterSuccess);
        burnCtrl->SetIsSwitchAfterLoader(switchAfterLoader);
    }
    SaveSettingCfg();
}

void WifiBurnDlg::SlotSetBurninterval()
{
    int burnInterval = comboBoxBurnInterval->currentText().toInt();
    if (burnInterval < MIN_BURN_INTERVAL || burnInterval > MAX_BURN_INTERVAL) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
            stringClass.GetBurnIntervalValueTips());
        return;
    }
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    burnCtrl->SetPeriod(burnInterval);
}

void WifiBurnDlg::SlotSaveConfig()
{
    SaveDlgConfig();
    if (isMultipleBurnOpen) {
        return;
    }
    QString pathWifi = DataConvertor::GetBurnToolConfigPathNew();
    if (QMessageBox::information(this, stringClass.GetInformation(),
                                 stringClass.GetOutPutConfigFile(),
                                 stringClass.GetYes(),
                                 stringClass.GetNo()) == 1) {
        return;
    }
    QString str = tr("Select File");
    QString filePathWifi = QFileDialog::getSaveFileName(this, str, "", stringClass.GetIdsString33074());
    if (filePathWifi.isEmpty() || pathWifi == filePathWifi) {
        return;
    }
    QFile file(filePathWifi);
    if (file.exists()) {
        int ret = QMessageBox::warning(nullptr, "", stringClass.GetIdsString33075(),
                                       stringClass.GetYes(), stringClass.GetNo());
        if (ret == 1) {
            return;
        }
        file.remove();
    }
    file.copy(pathWifi, filePathWifi);
}


void WifiBurnDlg::SaveDlgConfig()
{
    QString configPathFile = DataConvertor::GetBurnToolConfigPathNew();
    QFile file(configPathFile);
    if (file.exists()) {
        // 存在
        int resultWifi = QMessageBox::information(this, stringClass.GetInformation(),
                                                  stringClass.GetIdsString33075(), stringClass.GetYes(),
                                                  stringClass.GetNo());
        if (resultWifi == 1) {
            return;
        }
    }
    if (!(file.open(QIODevice::ReadWrite | QIODevice::Text))) {
        return;
    }
    file.close();
    // 保存串口设置
    SavedComConfig2File(configPathFile);
    // 保存文件信息
    SavedBinInfoConfig2File(configPathFile);
    // 保存窗口信息
    SavedWinInfoConfig2File(configPathFile);
}

void WifiBurnDlg::SlotButtonClickedCom()
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy() || ui == nullptr) {
        return;
    }
    if (portType == Base::SERIAL_PORT) {
        portType = Base::DFU_PORT;
        ui->btnCom->setText("DFU");
        if (burnCtrl->IsComOpen()) {
            burnCtrl->SwitchToDfu();
            ResetUIAndFSM();
            SlotInsertPlainText(stringClass.GetIdsString32895());
            burnCtrl = burnCtrlManager[1];
            // 清空网口，刷新串口
            SlotCbnSetfocusComboCom();
            ui->comboBoxCom->setEnabled(false);
            SlotBnClickedButtonConn();
        } else {
            burnCtrl = burnCtrlManager[1];
            // 清空网口，刷新串口
            SlotCbnSetfocusComboCom();
            ui->comboBoxCom->setEnabled(false);
        }
    } else if (portType == Base::TCP_PORT) {
        portType = Base::TCP_PORT;
        ui->btnCom->setText("TCP");
        // 清空串口，设置默认ip和port
        ui->comboBoxCom->clear();
        QString path = DataConvertor::GetBurnToolConfigPathNew();
        QSettings cfg(path, QSettings::IniFormat);
        QString ipInfo = cfg.value(IP_CONFIG + "/" + INI_IP_INFO).toString();
        if (!ipInfo.isEmpty()) {
            ui->comboBoxCom->addItem(ipInfo);
        }
        burnCtrl = burnCtrlManager[0];
    } else if (portType == Base::DFU_PORT) {
        portType = Base::SERIAL_PORT;
        ui->btnCom->setText("COM");
        burnCtrl = burnCtrlManager[0];
        ui->comboBoxCom->setEnabled(true);
    }
}

void WifiBurnDlg::InitBurnCtrl()
{
    BurnCtrlFaction faction;
    burnCtrlManager[0] = faction.GetBurnCtrl(chipType);
    burnCtrlManager[1] = faction.GetBurnCtrl(ChipType::DFU);
    burnCtrl = burnCtrlManager[1];
    if (burnCtrl != nullptr) {
        burnCtrl->SetBurnDlg(this);
    }
    burnCtrl = burnCtrlManager[0];
    if (burnCtrl != nullptr) {
        burnCtrl->SetBurnDlg(this);
    }
}

void WifiBurnDlg::GetComSettingFromGloble(int &baud, int &databits, int &stopbits,
                                          QSerialPort::Parity &parity, int &flowctrl) const
{
    SEBOOT_SHAKE_HANDS_FRAME *headVal =
        reinterpret_cast<SEBOOT_SHAKE_HANDS_FRAME *>(Global::shakeHandSignal);
    baud = headVal->baudRate;
    databits = headVal->dataBits;
    stopbits = headVal->stopBits;
    if (headVal->parity == 0) {
        parity = QSerialPort::NoParity;
    } else if (headVal->parity == 1) {
        parity = QSerialPort::OddParity;
    } else {
        parity = QSerialPort::EvenParity;
    }
    flowctrl = headVal->flowctrl;
}

void WifiBurnDlg::SetComSettingToGloble(int baud, int databits, int stopbits,
                                        QSerialPort::Parity parity, int flowctrl) const
{
    SEBOOT_SHAKE_HANDS_FRAME *headVal =
        reinterpret_cast<SEBOOT_SHAKE_HANDS_FRAME *>(Global::shakeHandSignal);
    headVal->baudRate = baud;
    headVal->dataBits = databits;
    headVal->stopBits = stopbits;
    if (parity == QSerialPort::EvenParity) {
        headVal->parity = 2; // even check trans to 2
    } else if (parity == QSerialPort::OddParity) {
        headVal->parity = 1;
    } else {
        headVal->parity = 0;
    }
    headVal->flowctrl = flowctrl;
    headVal->checkSum = ChannelClass::Channel::SopCrc16(static_cast<PBYTE>(Global::shakeHandSignal),
        SHAKE_HAND_SIGNAL_LEN - 2); // crc16 is 2
}

void WifiBurnDlg::SlotBnClickedButtonSelectfile()
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    QString filePath = QFileDialog::getOpenFileName(this, tr("Select File"), "", stringClass.GetIdsString32941());
    if (!filePath.isEmpty()) {
        AnalyseBinFile(filePath);
    }
    burnCtrl->SetBurnFileName(filePath);
}

void WifiBurnDlg::SavedComConfig2File(const QString &path) const
{
    if (ui == nullptr) {
        return;
    }
    int baud = 0;
    int databits = 0;
    int stopbits = 0;
    QSerialPort::Parity parity;
    int flowctrl = 0;
    GetComSettingFromGloble(baud, databits, stopbits, parity, flowctrl);
    QString strValue;
    QSettings cfg(path, QSettings::IniFormat);
    cfg.setValue(COM_CONFIG + "/" + INI_BAUD, QString::number(baud));
    cfg.setValue(COM_CONFIG + "/" + INI_DATABIT, QString::number(databits));
    cfg.setValue(COM_CONFIG + "/" + INI_STOPBIT, QString::number(stopbits));
    cfg.setValue(COM_CONFIG + "/" + INI_PARITY, QString::number(parity));
    cfg.setValue(COM_CONFIG + "/" + INI_FLOWCTRL, QString::number(flowctrl));
    QString currentCom = ui->comboBoxCom->currentText();
    cfg.setValue(COM_CONFIG + "/" + INI_COM, currentCom);
    cfg.setValue(IP_CONFIG + "/" + INI_IP_INFO, currentCom);
}

void WifiBurnDlg::SavedBinInfoConfig2File(const QString &path) const
{
    if (binModel == nullptr) {
        return;
    }
    QMap<int, BIN_INFO> info = binModel->GetBinFileInfoData();
    QSettings cfg(path, QSettings::IniFormat);
    cfg.remove("FILE_CONFIG");
    for (int i = 0; i < info.size(); i++) {
        BIN_INFO itemWifi = info[i];
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_CHECK + QString::number(i), QString::number(binModel->GetCheck(i)));
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_PATH + QString::number(i), itemWifi.path);
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_NAME + QString::number(i), itemWifi.fileName);
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_INDEX + QString::number(i), itemWifi.fileIndex);
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_SIZE + QString::number(i), itemWifi.fileSize);
        cfg.setValue(FILE_CONFIG + "/" + INI_BURN_ADDR + QString::number(i), itemWifi.burnAddr);
        cfg.setValue(FILE_CONFIG + "/" + INI_BURN_SIZE + QString::number(i), itemWifi.burnSize);
        cfg.setValue(FILE_CONFIG + "/" + INI_FILE_TYPE + QString::number(i),
                     QString::number(static_cast<int>(itemWifi.type)));
    }
}

void WifiBurnDlg::SavedWinInfoConfig2File(const QString &path) const
{
    if (ui == nullptr || burnCtrl == nullptr) {
        return;
    }
    QSettings cfg(path, QSettings::IniFormat);
    cfg.setValue(DLG_CONFIG + "/" + "CHIP_TYPE", QString::number(static_cast<int>(chipType)));
    cfg.setValue(DLG_CONFIG + "/" + "DLG_BURN_NUM", QString::number(burnCtrl->GetMultiBurnTotalNum()));
    cfg.setValue(DLG_CONFIG + "/" + "DLG_ONE_LINE_NUM", QString::number(burnCtrl->GetMultiBurnNumPerLine()));
    cfg.setValue(DLG_CONFIG + "/" + "DLG_INDENPENDENT_BURN", QString::number(burnCtrl->GetMultiBurnIndenpendentBurn()));
    cfg.setValue(DLG_CONFIG + "/" + "REOPEN_COM", QString::number(burnCtrl->GetMultiBurnReopenCom()));
    cfg.setValue(DLG_CONFIG + "/" + "MULTIPLE_BURN", QString::number(isMultipleBurnOpen));
    cfg.setValue(DLG_CONFIG + "/" + "ERASE_MODE", ui->comBoxEarseMode->currentText());
    cfg.setValue(DLG_CONFIG + "/" + "CONFIRM_CONNECT_SLEEP_TIMEOUT", QString::number(NUMBER_ONE_HUNDRED));
    cfg.setValue(DLG_CONFIG + "/" + "CONFIRM_CONNECT_WAIT_TIMEOUT", QString::number(NUMBER_TWO_HUNDRED));
    cfg.setValue(DLG_CONFIG + "/" + "FORCE_READ_FLAG", QString::number(burnCtrl->GetForceReadFlag()));
    cfg.setValue(DLG_CONFIG + "/" + "YMODEM_PACKAGE_SIZE", QString::number(burnCtrl->GetYModemEachPackageSize()));
    cfg.setValue(DLG_CONFIG + "/" + "RESET_AFTER_SUCCESS", QString::number(burnCtrl->GetIsResetAfterSuccess()));
    cfg.setValue(DLG_CONFIG + "/" + "SWITCH_BAUD_RATE_AFTER_LOADER",
                 QString::number(burnCtrl->GetIsSwitchAfterLoader()));
    cfg.setValue(DLG_CONFIG + "/" + "AUTO_BURN", QString::number(ui->checkBoxAutoBurn->checkState()));
    cfg.setValue(DLG_CONFIG + "/" + "AUTO_DISCONNECT", QString::number(ui->checkBoxAutoDisconnect->checkState()));
}

void WifiBurnDlg::LoadDlgConfig() const
{
    QString path = DataConvertor::GetBurnToolConfigPathNew();

    LoadComConfigFromFile(path);
    LoadFileConfigFromFile(path);
}

void WifiBurnDlg::LoadComConfigFromFilePartOne(const QSettings &cfg) const
{
    burnCtrl->SetMultiBurnIndenpendentBurn(cfg.value(DLG_CONFIG + "/" + "DLG_INDENPENDENT_BURN").toBool());
    burnCtrl->SetIsResetAfterSuccess(cfg.value(DLG_CONFIG + "/" + "RESET_AFTER_SUCCESS").toBool());
    burnCtrl->SetIsSwitchAfterLoader(cfg.value(DLG_CONFIG + "/" + "SWITCH_BAUD_RATE_AFTER_LOADER").toBool());
    int packageSize = cfg.value(DLG_CONFIG + "/" + "YMODEM_PACKAGE_SIZE").toInt();
    if (packageSize > YMODEM_MAX_PACKAGE_SIZE) {
        packageSize = YMODEM_MAX_PACKAGE_SIZE;
    }
    burnCtrl->SetYModemEachPackageSize(packageSize);
    QString cfgEraseMode = cfg.value(DLG_CONFIG + "/" + "ERASE_MODE").toString();
    int index = ui->comBoxEarseMode->findText(cfgEraseMode);
    if (index != -1) {
        ui->comBoxEarseMode->setCurrentIndex(index);
    }
    ui->checkBoxAutoBurn->setCheckState(static_cast<Qt::CheckState>(cfg.value(DLG_CONFIG + "/" + "AUTO_BURN").toInt()));
    ui->checkBoxAutoDisconnect->setCheckState(static_cast<Qt::CheckState>( \
                                              cfg.value(DLG_CONFIG + "/" + "AUTO_DISCONNECT").toInt()));
    burnCtrl->SetReopenComFlag(static_cast<Qt::CheckState>(cfg.value(DLG_CONFIG + "/" + "REOPEN_COM").toInt()));
    burnCtrl->SetMultiBurnTotalNum(cfg.value(DLG_CONFIG + "/" + "DLG_BURN_NUM").toUInt());
    burnCtrl->SetMultiBurnNumPerLine(cfg.value(DLG_CONFIG + "/" + "DLG_ONE_LINE_NUM").toUInt());
}

void WifiBurnDlg::LoadComConfigFromFile(const QString &path) const
{
    if (ui == nullptr || burnCtrl == nullptr) {
        return;
    }
    unsigned int ret = 1;
    QSettings cfg(path, QSettings::IniFormat);
    QVariant ascReturnedBaud = cfg.value(COM_CONFIG + "/" + INI_BAUD);
    ret &= static_cast<unsigned int>(ascReturnedBaud.isValid());
    int baudRate = ascReturnedBaud.toInt();
    QVariant ascReturnedDataBit = cfg.value(COM_CONFIG + "/" + INI_DATABIT);
    ret &= static_cast<unsigned int>(ascReturnedDataBit.isValid());
    int databit = ascReturnedDataBit.toInt();
    QVariant ascReturnedStopBit = cfg.value(COM_CONFIG + "/" + INI_STOPBIT);
    ret &= static_cast<unsigned int>(ascReturnedStopBit.isValid());
    int stopbit = ascReturnedStopBit.toInt();
    QVariant ascReturnedParity = cfg.value(COM_CONFIG + "/" + INI_PARITY);
    ret &= static_cast<unsigned int>(ascReturnedParity.isValid());
    QSerialPort::Parity parity = static_cast<QSerialPort::Parity>(ascReturnedParity.toInt());
    QVariant ascReturnedFlowCtrl = cfg.value(COM_CONFIG + "/" + INI_FLOWCTRL);
    ret &= static_cast<unsigned int>(ascReturnedFlowCtrl.isValid());
    int flowCtrl = ascReturnedFlowCtrl.toInt();
    if (portType == Base::SERIAL_PORT && ret == 1) {
        SetComSettingToGloble(baudRate, databit, stopbit, parity, flowCtrl);
    }
    QString com = cfg.value(COM_CONFIG + "/" + INI_COM).toString();
    int index = ui->comboBoxCom->findText(com);
    if (index != -1) {
        ui->comboBoxCom->setCurrentIndex(index);
    }
    if (portType == Base::TCP_PORT) {
        QString ipInfo = cfg.value(IP_CONFIG + "/" + INI_IP_INFO).toString();
        if (ipInfo.contains(":")) {
            ui->comboBoxCom->setEditText(ipInfo);
        }
    }

    LoadComConfigFromFilePartOne(cfg);
}

void WifiBurnDlg::LoadFileConfigFromFile(const QString &path) const
{
    if (binModel == nullptr) {
        return;
    }
    QMap<int, BIN_INFO> info;
    QSettings cfg(path, QSettings::IniFormat);
    QMap<int, BIN_INFO> mapBinInfo;
    mapBinInfo.clear();
    for (unsigned int i = 0; i < EFUSE_ITEM_MAX; ++i) {
        BIN_INFO infoWifi;
        unsigned int ret = BurnDlg::LoadFileConfigFromFileGetInfo(infoWifi, cfg, i);
        if (ret == 0) {
            break;
        }
        mapBinInfo[i] = infoWifi;
    }
    binModel->FetchData(mapBinInfo);

    QMap<int, bool> mapCheck;
    for (unsigned int i = 0; i < EFUSE_ITEM_MAX; ++i) {
        bool ret = true;
        QVariant check = cfg.value(FILE_CONFIG + "/" + INI_FILE_CHECK + QString::number(i));
        ret = check.isValid();
        if (!ret) {
            break;
        }
        mapCheck[i] = check.toBool();
    }
    binModel->FetchData(mapCheck);
    if (ui != nullptr) {
        ui->lineEditSeleteFile->setText(mapBinInfo[0].path);
    }
}

void WifiBurnDlg::ResetUIAndFSM()
{
    if (ui == nullptr) {
        return;
    }
    BurnDlg::ResetUIAndFSM();
    ui->btnConnect->setText(stringClass.GetIdsString32918());
    ui->progressBarReceive->setValue(0);
}

void WifiBurnDlg::SlotBnClickedButtonStartburn()
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    if (!burnCtrl->IsComOpen()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32976(), stringClass.GetYes());
        return;
    }
    UpdateList();
    if (!CheckAllPathInGrid(true)) {
        return;
    }
    U32 ret = burnCtrl->SendBurnCmd();
    if (ret == ERR_SOP_CPAB_NOT_CONNECT_UE) {
        QMessageBox::critical(this, stringClass.GetMessageError(), stringClass.GetIdsString32944());
    } else if (ret == ERR_SOP_BUSY) {
        QMessageBox::critical(this, stringClass.GetMessageError(), stringClass.GetIdsString32945());
    } else if (ret == ERR_SOP_FILE_NOT_FOUND || ret == ERR_SOP_INVALID_PARAMETERS) {
        QMessageBox::critical(this, stringClass.GetMessageError(), stringClass.GetIdsString32946());
    }
    return;
}

void WifiBurnDlg::SlotBnClickedSelectTarget()
{
    QString filePath = QFileDialog::getSaveFileName(this, tr("Select File"), "", stringClass.GetIdsString32949());
    if (!filePath.isEmpty()) {
        ui->lineEditSelectTarget->setText(filePath);
    }
}

void WifiBurnDlg::SlotBnClickedButtonConn()
{
    if (burnCtrl == nullptr) {
        return;
    }
    if (!burnCtrl->IsComOpen()) {
        UpdateList();
    }

    if (ui->checkBoxAutoBurn->checkState() == Qt::Checked && (!QFile(ui->lineEditSeleteFile->text()).exists())) {
        QMessageBox::warning(nullptr, tr("BurnTool"), stringClass.GetNoValidFlashFile());
        return;
    }

    burnCtrl->SetPortType(portType);
    if (portType == Base::TCP_PORT) {
        QString strPort = ui->comboBoxCom->currentText();
        const int idxColon = strPort.indexOf(':');
        if (idxColon == -1) {
            QMessageBox::warning(this, strPort, stringClass.GetIdsString33276());
            return;
        }
        QString strIpAddr = strPort.mid(0, idxColon);
        strIpAddr = strIpAddr.trimmed();
        QString strIpPort = strPort.mid(idxColon + 1);
        strIpPort = strIpPort.trimmed();
        burnCtrl->SetIpSetting(strIpAddr, DataConvertor::Str2U32DecHex(strIpPort));
    }

    if (burnCtrl->IsComOpen()) {
        ResetUIAndFSM();
        SlotInsertPlainText(stringClass.GetIdsString32895());
        return;
    }
    burnCtrl->UpdateComSetting(OPEN_SERIAL_PORT_DEFAULT_BAUD_RATE, OPEN_SERIAL_PORT_DEFAULT_DATA_BIT,
                               OPEN_SERIAL_PORT_DEFAULT_STOP_BIT, QSerialPort::NoParity,
                               OPEN_SERIAL_PORT_DEFAULT_FLOWCTRL);
    if (!ConfigComPort()) {
        return;
    }
    burnCtrl->SetAutoBurnFlag(isAutoBurn);
    burnCtrl->SetLoaderDfu(isLoaderDfu);

    if (isEncrypt && encryptBuffer.bufferData != nullptr && encryptBuffer.bufferLen != 0) {
        burnCtrl->SetIsEncrypt(isEncrypt);
        burnCtrl->SetEncryptBuffer(encryptBuffer.bufferData);
        burnCtrl->SetEncryptBufferLen(encryptBuffer.bufferLen);
    }
    SlotClearPlainText();
    SlotInsertPlainText(stringClass.GetIdsString32897());
    emit SignalSendMsgInBurnDlg(static_cast<long>(WiteThreadMsg::WITE_THREAD_MSG_STARTCONNECT), 0, 0);
    emit SignalSendMsgInBurnDlg(static_cast<long>(WiteThreadMsg::WITE_THREAD_MSG_INITBURNCMD), 0, 0);
    ui->btnConnect->setText(stringClass.GetDisconnect());
    return;
}

void WifiBurnDlg::UpdateCmd()
{
    if (burnCtrl == nullptr || binModel == nullptr) {
        return;
    }
    int nRowCount = binModel->rowCount();
    if (nRowCount > 0x1000) {
        return;
    }
    QMap<int, BIN_INFO> infoArray;
    GetBinInforArray(infoArray, nRowCount);
    if (burnCtrlManager[1] != nullptr) {
        burnCtrlManager[1]->InitBurnCmdByArray(infoArray);
    }

    if (burnCtrlManager[0] != nullptr) {
        burnCtrlManager[0]->InitBurnCmdByArray(infoArray);
    }
}

void WifiBurnDlg::GetCmdInfoArray(QMap<int, BIN_INFO> &infoArray) const
{
    if (binModel == nullptr) {
        return;
    }
    int nRow = binModel->rowCount();
    if (nRow > 0x1000) {
        return;
    }
    infoArray.clear();

    GetBinInforArray(infoArray, nRow);
}

void WifiBurnDlg::UpdateList()
{
    if (binModel == nullptr) {
        return;
    }
    int nRow = binModel->rowCount();
    if (nRow > 0x1000) {
        return;
    }
    std::vector<QString> pathArray;

    for (int i = 0; i < nRow; i++) {
        if (binModel->GetCheck(i)) {
            QString path = binModel->GetValue(i, TABLEVIEW_COLUMN_PAHT);
            pathArray.push_back(path);
        }
    }
    std::vector<QString> result;
    for (auto item : pathArray) {
        bool needAddWifi = true;
        for (auto item2 : result) {
            if (item2 == item) {
                needAddWifi = false;
                break;
            }
        }
        if (needAddWifi) {
            result.push_back(item);
        }
    }
    unsigned int needInitCmd = 0;
    QString version;
    for (auto item : result) {
        BIN_INFO_ARRAY infoArray;
        if (isEncrypt) {
            DataConvertor::AnalysMultifBin(item, infoArray, version, encryptBuffer);
        } else {
            DataConvertor::AnalysMultifBin(item, infoArray, version, isEncrypt, encryptBuffer);
        }
        needInitCmd |= static_cast<unsigned int>(UpdateList(infoArray));
    }
    if (needInitCmd != 0) {
        UpdateCmd();
    }
    UpdateVersion(version);
}

bool WifiBurnDlg::UpdateList(BIN_INFO_ARRAY &info) const
{
    if (binModel == nullptr) {
        return false;
    }
    bool needInitCmd = false;
    for (int i = 0; i < info.GetSize(); i++) {
        BIN_INFO item = info.GetAt(i);
        int colNum = binModel->rowCount(); // 取行数
        if (colNum > 0x1000) {
            break;
        }
        QMap<int, BIN_INFO> mapBinInfo;
        mapBinInfo.clear();
        mapBinInfo = binModel->GetMapBinFileInfo();
        for (int j = 0; j < colNum; j++) {
            if ((!item.fileName.isEmpty()) && binModel->GetCheck(j) &&
                 item.path == mapBinInfo[j].path && item.fileName == mapBinInfo[j].fileName &&
                 item.type == mapBinInfo[j].type && (mapBinInfo[j].fileIndex != item.fileIndex ||
                 mapBinInfo[j].fileSize != item.fileSize || mapBinInfo[j].burnAddr != item.burnAddr ||
                 mapBinInfo[j].burnSize != item.burnSize)) {
                mapBinInfo[j].fileIndex = item.fileIndex;
                mapBinInfo[j].fileSize = item.fileSize;
                mapBinInfo[j].burnAddr = item.burnAddr;
                mapBinInfo[j].burnSize = item.burnSize;
                needInitCmd = true;
            } else if (item.fileName.isEmpty() && binModel->GetCheck(j) && (item.path == mapBinInfo[j].path) &&
                       (item.fileName == mapBinInfo[j].fileName) && (item.fileSize != mapBinInfo[j].fileSize)) {
                mapBinInfo[j].fileSize = item.fileSize;
                needInitCmd = true;
            }
        }
        binModel->FetchData(mapBinInfo);
    }
    return needInitCmd;
}

void WifiBurnDlg::AnalyseBinFile(QString filePath)
{
    if (ui == nullptr || binModel == nullptr || burnCtrl == nullptr) {
        return;
    }
    ui->lineEditSeleteFile->setText(filePath);
    if (alwaysClear) {
        binModel->ClearData();
    }
    QMap<int, BIN_INFO> mapBinInfo;
    mapBinInfo = binModel->GetMapBinFileInfo();
    BIN_INFO_ARRAY binInfoArray;
    QString version;
    isEncrypt = false;
    if (encryptBuffer.bufferData != nullptr) {
        delete [] encryptBuffer.bufferData;
        encryptBuffer.bufferData = nullptr;
    }
    encryptBuffer.bufferLen = 0;
    burnCtrl->SetEncryptBuffer(encryptBuffer.bufferData);
    burnCtrl->SetEncryptBufferLen(encryptBuffer.bufferLen);
    burnCtrl->SetIsEncrypt(isEncrypt);
    DataConvertor::AnalysMultifBin(ui->lineEditSeleteFile->text(), binInfoArray, version,
                                   isEncrypt, encryptBuffer);
    int startImport = mapBinInfo.size();
    for (int i = 0; i < binInfoArray.GetSize(); i++) {
        mapBinInfo[startImport + i] = binInfoArray.GetAt(i);
    }
    QMap<int, bool> mapIsCheck;
    for (int i = 0; i < mapBinInfo.size(); i++) {
        if (chipType == ChipType::WIFI4GCAT1 && eraseMode == 1) {
            mapIsCheck[i] = true;
        } else {
            if (mapBinInfo[i].type == IMAGE_TYPE::IMAGE_TYPE_RADIOCONFIG ||
                mapBinInfo[i].type == IMAGE_TYPE::IMAGE_TYPE_FLASHBOOT_3892 ||
                IsSelectOtp(mapBinInfo[i].type)) {
                mapIsCheck[i] = false;
            } else {
                mapIsCheck[i] = true;
            }
        }
    }
    binModel->FetchData(mapIsCheck);
    binModel->FetchData(mapBinInfo);
    UpdateVersion(version);
}

void WifiBurnDlg::SlotNMKillfocusListBinPath(const NMHDR *pNMHDR, LRESULT *pResult)
{
    Q_UNUSED(pNMHDR);
    if (burnCtrl == nullptr || burnCtrl->IsBusy() || pResult == nullptr || binModel == nullptr) {
        return;
    }
    UpdateList();
    int nRowCount = binModel->rowCount();
    if (nRowCount > 0x1000) {
        return;
    }
    QMap<int, BIN_INFO> infoArray;

    GetBinInforArray(infoArray, nRowCount);
    burnCtrl->InitBurnCmdByArray(infoArray);
    *pResult = 0;
}

void WifiBurnDlg::SlotLvnItemchangedListBinPath(const QModelIndex &topLeft, const QModelIndex &bottomRight,
                                                const QVector<int> &roles)
{
    Q_UNUSED(topLeft);
    Q_UNUSED(bottomRight);
    Q_UNUSED(roles);
    if (burnCtrl == nullptr) {
        return;
    }
    if (burnCtrl->IsBusy()) {
        return;
    }
    if (isInserting) {
        return;
    }

    UpdateList();
    UpdateCmd();
    JudgeIsSelectAll();
}

void WifiBurnDlg::SlotmodelReset()
{
    if (burnCtrl == nullptr) {
        return;
    }
    if (burnCtrl->IsBusy()) {
        return;
    }
    if (isInserting) {
        return;
    }

    UpdateCmd();
    JudgeIsSelectAll();
}

void WifiBurnDlg::SlotBnClickedExport()
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    if (!burnCtrl->IsComOpen()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32976(), stringClass.GetYes());
        return;
    }
    if (ui == nullptr) {
        return;
    }
    QString addr = ui->lineEditAddr->text();
    QString size = ui->lineEditSize->text();
    QString path = ui->lineEditSelectTarget->text();
    burnCtrl->StartUpload(path, DataConvertor::Str2U32DecHex(addr), DataConvertor::Str2U32DecHex(size));
}

void WifiBurnDlg::SlotBnClickedButtonReadEfuse()
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    if (!burnCtrl->IsComOpen()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32976(), stringClass.GetYes());
        return;
    }
    if (ui == nullptr) {
        return;
    }
    int i = ui->comBoxEfuse->currentIndex();
    if (i >= 0 && efuseStartBit.size() > 0) {
        burnCtrl->ReadEfuse(efuseStartBit[i], efuseBitWidth[i]);
    } else {
        burnCtrl->ReadEfuse(0, 0);
    }
}

void WifiBurnDlg::SlotBnClickedButtonImportEfuseConfig()
{
    if (ui == nullptr) {
        return;
    }
    QFileDialog fileDialog;
    fileDialog.setWindowTitle(tr("Select File"));
    fileDialog.setDirectory(".");
    fileDialog.setNameFilter(stringClass.GetIdsString33074());
    fileDialog.setFileMode(QFileDialog::ExistingFiles);
    fileDialog.setViewMode(QFileDialog::Detail);
    if (fileDialog.exec() == QFileDialog::Rejected) {
        return;
    }
    QStringList filePath = fileDialog.selectedFiles();
    if (filePath.size() <= 0) {
        return;
    }

    QString path = filePath[0];
    ui->comBoxEfuse->clear();
    QStringList efuseNameList;
    efuseStartBit.clear();
    efuseStartBit.clear();
    QSettings cfg(path, QSettings::IniFormat);
    int maxLen = 0;
    for (unsigned int i = 0; i < EFUSE_ITEM_MAX; ++i) {
        QString ascReturnedString1 = cfg.value(INI_EFUSE_CONFIG + "/" + INI_EFUSE_NAME +
                                               QString::number(i + 1)).toString();
        QString ascReturnedString2 = cfg.value(INI_EFUSE_CONFIG + "/" + INI_EFUSE_START_BIT +
                                               QString::number(i + 1)).toString();
        QString ascReturnedString3 = cfg.value(INI_EFUSE_CONFIG + "/" + INI_EFUSE_BIT_WIDTH +
                                               QString::number(i + 1)).toString();
        if (ascReturnedString1.isEmpty() || ascReturnedString2.isEmpty() || ascReturnedString3.isEmpty()) {
            continue;
        }
        efuseStartBit[i] = DataConvertor::Str2U32DecHex(ascReturnedString2);
        efuseBitWidth[i] = DataConvertor::Str2U32DecHex(ascReturnedString3);
        efuseName[i] = ascReturnedString1;
        efuseNameList.push_back(ascReturnedString1);
        int strlen = ascReturnedString1.length();
        if (maxLen < strlen) {
            maxLen = strlen;
        }
    }

    ui->comBoxEfuse->addItems(efuseNameList);
    ui->comBoxEfuse->setCurrentIndex(0);
}

void WifiBurnDlg::SlotBnClickedReset()
{
    if (burnCtrl == nullptr) {
        return;
    }
    QString path = DataConvertor::GetBurnToolConfigPathNew();
    QSettings cfg(path, QSettings::IniFormat);
    QString cmd = cfg.value("at_command/reset").toString();
    QString resetCmd = Global::GetAtReset(chipType);
    if (!resetCmd.isEmpty()) {
        burnCtrl->AtReset(resetCmd);
    }
    if (!burnCtrl->IsBusy()) {
        burnCtrl->ResetByCmd();
    }
}

void WifiBurnDlg::SlotBnClickedTableHeader(int logicalIndex)
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    BurnDlg::SlotBnClickedTableHeader(logicalIndex);

    UpdateCmd();
}

void WifiBurnDlg::JudgeIsSelectAll() const
{
    if (binModel == nullptr) {
        return;
    }
    BOOL setcheck = TRUE;
    int nRowCount = binModel->rowCount();
    if (nRowCount > 0x1000) {
        return;
    }
    for (int i = 0; i < nRowCount; i++) {
        setcheck = static_cast<BOOL>(static_cast<UINT>(setcheck) & static_cast<UINT>(binModel->GetCheck(i)));
    }
}

void WifiBurnDlg::SlotBnClickedMultipleBurn()
{
    if (burnCtrl == nullptr || ui == nullptr) {
        return;
    }
    if (!isMultipleBurnOpen) {
        QMap<int, BIN_INFO> infoArray;
        GetCmdInfoArray(infoArray);
        if (infoArray.size() == 0) {
            QMessageBox::critical(this, stringClass.GetMessageError(),
                                  stringClass.GetIdsString33069(), stringClass.GetYes());
            return;
        }
        int result = QMessageBox::information(this, stringClass.GetInformation(), stringClass.GetIdsString33070(),
                                              stringClass.GetYes(), stringClass.GetNo());
        if (result == 1) {
            return;
        }
        isMultipleBurnOpen = true;
        if (burnCtrl->IsComOpen()) {
            emit SignalSendMsgInBurnDlg(static_cast<long int>(WiteThreadMsg::WITE_THREAD_MSG_RESETUIANDFSM), 0, 0);
            ui->btnConnect->setText(stringClass.GetIdsString32918());
        }
        ui->btnConnect->setEnabled(false);
        ui->btnSendFile->setEnabled(false);
        FillParamAndShow(infoArray);
    }
}

void WifiBurnDlg::FillParamAndShow(const QMap<int, BIN_INFO> &info)
{
    if (multipleBurnDlg != nullptr) {
        delete multipleBurnDlg;
        multipleBurnDlg = nullptr;
    }
    multipleBurnDlg = new MultipleBurnDlg();
    if (multipleBurnDlg == nullptr) {
        isMultipleBurnOpen = false;
        return;
    }
    if (ui == nullptr || burnCtrl == nullptr) {
        return;
    }
    multipleBurnDlg->SetChipType(chipType);
    multipleBurnDlg->SetAutoBurnFlag();
    multipleBurnDlg->SetReopenComFlag(burnCtrl->GetMultiBurnReopenCom());
    multipleBurnDlg->SetIsResetAfterSuccess(burnCtrl->GetIsResetAfterSuccess());
    multipleBurnDlg->SetBootType(burnCtrl->GetBootType());
    int mode = ui->comBoxEarseMode->currentIndex();
    multipleBurnDlg->SetEraseAll(mode);
    multipleBurnDlg->SetSecConn(burnCtrl->IsSecConn());
    multipleBurnDlg->SetPeriod(burnCtrl->GetPeriod());

    int baud = 0;
    int databits = 0;
    int stopbits = 0;
    QSerialPort::Parity parity;
    int flowctrl = 0;
    burnCtrl->GetComSetting(baud, databits, stopbits, parity, flowctrl);
    multipleBurnDlg->UpdateComSetting(baud, databits, stopbits, parity, flowctrl);
    multipleBurnDlg->SetForceReadTime(burnCtrl->GetForceReadTime());
    multipleBurnDlg->SetForceReadFlag(burnCtrl->GetForceReadFlag());
    multipleBurnDlg->SetConfirmConnectSleepTime(burnCtrl->GetConnectConfirmSleepTimeout());
    multipleBurnDlg->SetConfirmConnectWaitTime(burnCtrl->GetConnectConfirmWaitTimeout());
    multipleBurnDlg->SetInfoArray(info);
    multipleBurnDlg->SetIndenpendentBurn(burnCtrl->GetMultiBurnIndenpendentBurn());
    multipleBurnDlg->SetYModemEachPackageSize(burnCtrl->GetYModemEachPackageSize());
    multipleBurnDlg->SetIsSwitchAfterLoader(burnCtrl->GetIsSwitchAfterLoader());
    QString strFilePath = ui->lineEditSeleteFile->text();
    multipleBurnDlg->SetInfoArray(strFilePath);
    connect(multipleBurnDlg, &MultipleBurnDlg::SignalClose, this, &WifiBurnDlg::SlotMultipleBurnDlgClose);
    connect(multipleBurnDlg, &MultipleBurnDlg::SignalSaveDlgConfig, this, &WifiBurnDlg::SlotSaveConfig);
    connect(multipleBurnDlg, &MultipleBurnDlg::SignalUpdateList, this, &WifiBurnDlg::SlotUpdateList);
    multipleBurnDlg->SetCtrlNum(burnCtrl->GetMultiBurnTotalNum());
    multipleBurnDlg->SetOneLineNum(burnCtrl->GetMultiBurnNumPerLine());
    multipleBurnDlg->SetIsEncrypt(isEncrypt);
    multipleBurnDlg->SetEncryptBuffer(encryptBuffer);
    multipleBurnDlg->InitUi();
    multipleBurnDlg->show();
}

void WifiBurnDlg::SlotMultipleBurnDlgClose()
{
    if (ui == nullptr) {
        return;
    }
    isMultipleBurnOpen = false;
    ui->btnConnect->setEnabled(true);
    ui->btnSendFile->setEnabled(true);
}

void WifiBurnDlg::SlotImportConfig()
{
    QString pathWifi = DataConvertor::GetBurnToolConfigPathNew();
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
    QString filePath = QFileDialog::getOpenFileName(this, tr("Select File"), "", stringClass.GetIdsString33074());
    if (filePath.isEmpty() || pathWifi == filePath) {
        return;
    }
    QFile file(pathWifi);
    if (file.exists()) {
        if (QMessageBox::warning(nullptr, "", stringClass.GetIdsString33075(),
            stringClass.GetYes(), stringClass.GetNo()) == 1) {
            return;
        }
        file.remove();
    }
    file.copy(filePath, pathWifi);

    QSettings cfg(pathWifi, QSettings::IniFormat);
    int chipTypeIni = cfg.value(DLG_CONFIG + "/" + "CHIP_TYPE").toInt();
    if (chipTypeIni != static_cast<int>(Global::currentChipTypeId)) {
        QSettings cfg2(Global::GetAppConfigPath() + "\\config_chip_type.ini", QSettings::IniFormat);
        cfg2.setValue("ChipType/CurrentChipTypeId", QString::number(chipTypeIni));
        Global::CloseApp(QAPP_EXIT_VALUE);
    }
    LoadDlgConfig();
}

void WifiBurnDlg::GetBinInforArray(QMap<int, BIN_INFO> &infoArray, int row) const
{
    if (binModel == nullptr) {
        return;
    }
    for (int i = 0, j = 0; i < row; i++) {
        if (binModel->GetCheck(i)) {
            BIN_INFO infor;
            infor.fileName = binModel->GetValue(i, TABLEVIEW_COLUMN_NAME);
            infor.path = binModel->GetValue(i, TABLEVIEW_COLUMN_PAHT);
            infor.fileIndex = binModel->GetValue(i, TABLEVIEW_COLUMN_FILE_INDEX);
            infor.fileSize = binModel->GetValue(i, TABLEVIEW_COLUMN_FILE_SIZE);
            infor.burnAddr = binModel->GetValue(i, TABLEVIEW_COLUMN_BURN_ADDR);
            infor.burnSize = binModel->GetValue(i, TABLEVIEW_COLUMN_BURN_SIZE);
            infor.type = binModel->GetType(i);
            infoArray[j++] = infor;
        }
    }
}

void WifiBurnDlg::GetAllPathFromGrid(std::vector<QString> &path) const
{
    for (int i = 0; i < binModel->rowCount(); i++) {
        if (binModel->GetCheck(i)) {
            path.push_back(binModel->GetValue(i, TABLEVIEW_COLUMN_PAHT));
        }
    }
}

bool WifiBurnDlg::CheckAllPathInGrid(bool onlyNotify)
{
    std::vector<QString> path;
    GetAllPathFromGrid(path);
    return CheckAllPath(path, onlyNotify);
}

bool WifiBurnDlg::CheckAllPath(std::vector<QString> &path, bool onlyNotify)
{
    bool ret = true;
    std::vector<QString> result;
    if (!DataConvertor::AllPathFileExists(path, result)) {
        QString strLog = stringClass.GetIdsString33270();
        for (auto item : result) {
            strLog += item;
            strLog += "\n";
        }
        if (onlyNotify) {
            if (QMessageBox::warning(this, stringClass.GetMessageError(), strLog, stringClass.GetOk(),
                                     stringClass.GetCancel()) == 1) {
                ret = false;
            }
        } else {
            QMessageBox::warning(this, stringClass.GetMessageError(), strLog);
        }
    }
    return ret;
}

void WifiBurnDlg::SlotEarseModeCurrentIndexChanged(int index)
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        ui->comBoxEarseMode->blockSignals(true);
        ui->comBoxEarseMode->setCurrentIndex(eraseMode);
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        ui->comBoxEarseMode->blockSignals(false);
        return;
    }
    eraseMode = index;
    burnCtrl->SetEraseMode(eraseMode);

    QMap<int, bool> mapCheck;
    QMap<int, BIN_INFO> mapBinInfo = binModel->GetMapBinFileInfo();
    for (int j = 0; j < mapBinInfo.size(); j++) {
        // 4GCAT1 UART烧写模式下erase all场景默认全选所有文件
        if (chipType == ChipType::WIFI4GCAT1 && eraseMode == 1) {
            mapCheck[j] = true;
        } else {
            if (mapBinInfo[j].type == IMAGE_TYPE::IMAGE_TYPE_RADIOCONFIG ||
                mapBinInfo[j].type == IMAGE_TYPE::IMAGE_TYPE_FLASHBOOT_3892 ||
                IsSelectOtp(mapBinInfo[j].type)) {
                mapCheck[j] = false;
            } else {
                mapCheck[j] = true;
            }
        }
    }
    binModel->FetchData(mapCheck);

    LRESULT ret = 0;
    SlotNMKillfocusListBinPath(nullptr, &ret);
}

void WifiBurnDlg::SlotBnClickedEraseAll() const
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        return;
    }
    burnCtrl->EraseAllByCmd();
}

void WifiBurnDlg::SlotCbnSetfocusComboCom() const
{
    if (portType == Base::TCP_PORT) {
        return;
    }
    if (ui == nullptr) {
        return;
    }
    QString strPort = ui->comboBoxCom->currentText();
    ui->comboBoxCom->clear();
    QStringList strListPortWifi;
    DataConvertor::RefreshComList(strListPortWifi);
    ui->comboBoxCom->addItems(strListPortWifi);
    for (int i = 0; i < strListPortWifi.size(); i++) {
        if (strListPortWifi.at(i) == strPort) {
            ui->comboBoxCom->setCurrentText(strPort);
        }
    }
}

void WifiBurnDlg::UpdateVersion(const QString &version) const
{
    if (ui == nullptr) {
        return;
    }
    if (!version.isEmpty()) {
        QString strVersion = tr("Version ") + version;
        ui->verson->setText(strVersion);
    } else {
        ui->verson->setText(version);
    }
}

LRESULT WifiBurnDlg::SlotSwitchDfu(WPARAM wParam, LPARAM lParam)
{
    if (burnCtrl == nullptr) {
        return 0;
    }
    if (burnCtrl->IsComOpen() && wParam == 0 && lParam == 0) {
        burnCtrl->SwitchToDfu();
        portType = Base::DFU_PORT;
        ui->btnCom->setText("DFU");
        ResetUIAndFSM();
        SlotInsertPlainText(stringClass.GetIdsString32895());
        burnCtrl = burnCtrlManager[1];
        // 清空网口，刷新串口
        ui->btnCom->setEnabled(false);
        Sleep(500); // 500: sleeptime
        SlotBnClickedButtonConn();
    }
    return 0;
}

void WifiBurnDlg::SlotCheckAutoBurnStateChanged(int state)
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        return;
    }
    if (state == Qt::Checked) {
        isAutoBurn = true;
    } else {
        isAutoBurn = false;
    }
    burnCtrlManager[1]->SetAutoBurnFlag(isAutoBurn);
    UpdateCmd();
}

void WifiBurnDlg::SlotAutoBurnClick(bool checked)
{
    if (ui == nullptr) {
        return;
    }
    Q_UNUSED(checked);
    if (burnCtrl == nullptr || burnCtrl->IsBusy()) {
        ui->checkBoxAutoBurn->setCheckState(isAutoBurn ? Qt::Checked : Qt::Unchecked);
        QMessageBox::critical(this, stringClass.GetMessageError(),
                              stringClass.GetIdsString32984(), stringClass.GetYes());
        return;
    }
}

void WifiBurnDlg::SlotCheckAutoDisconnectStateChanged(int state)
{
    if (state == Qt::Checked) {
        isAutoDisconnect = true;
    } else {
        isAutoDisconnect = false;
    }
    burnCtrl->SetAutoDisconnectFlag(isAutoDisconnect);
}

bool WifiBurnDlg::ConfigComPort()
{
    if (ui == nullptr || burnCtrl == nullptr) {
        return false;
    }
    QString strComPort = ui->comboBoxCom->currentText();
    if (portType == Base::TCP_PORT) {
        return burnCtrl->ConfigTcpPort();
    }
    if (portType == Base::DFU_PORT) {
        return true;
    }

    if (ui->comboBoxCom->findText(strComPort) != -1) {
        ui->comboBoxCom->setCurrentText(strComPort);
    }
    if (ui->comboBoxCom->count() == 0) {
        QMessageBox::warning(this, "", stringClass.GetIdsString32899());
        return false;
    } else {
        int com = strComPort.mid(3).toInt();
        if (burnCtrl != nullptr) {
            burnCtrl->SetComNum(com);
            return burnCtrl->ConfigComPort();
        }
        return false;
    }
}

void WifiBurnDlg::SlotAutoDisconnect(WPARAM wParam, LPARAM lParam)
{
    if (burnCtrl == nullptr) {
        return;
    }
    if (burnCtrl->IsComOpen() && wParam == 0 && lParam == 0) {
        ResetUIAndFSM();
        SlotInsertPlainText(stringClass.GetIdsString32895());
    }
}

void WifiBurnDlg::SlotInsertPlainText(const QString &editStr)
{
    if (ui == nullptr) {
        return;
    }
    QScrollBar *scrollbar = ui->textEditReceive->verticalScrollBar();

    bool scrollbarAtButtomVal = (scrollbar->value() >= scrollbar->maximum() - 50);
    int scrollbarPrevValue = scrollbar->value();
    QTextCursor cursor = ui->textEditReceive->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEditReceive->setTextCursor(cursor);
    ui->textEditReceive->insertPlainText(editStr);
    if (scrollbarAtButtomVal) {
        ui->textEditReceive->ensureCursorVisible();
    } else {
        ui->textEditReceive->verticalScrollBar()->setValue(scrollbarPrevValue);
    }
}

void WifiBurnDlg::SlotClearPlainText()
{
    if (ui == nullptr) {
        return;
    }
    ui->textEditReceive->clear();
}

void WifiBurnDlg::SlotReplacePlainText(const QString &oldText, const QString &newText)
{
    if (ui == nullptr) {
        return;
    }
    QString str = ui->textEditReceive->toPlainText();
    SlotClearPlainText();
    str.replace(oldText, newText);
    SlotInsertPlainText(str);
}

void WifiBurnDlg::SlotMergeCurrentCharFormat(const QTextCharFormat &fmt)
{
    if (ui == nullptr) {
        return;
    }
    ui->textEditReceive->mergeCurrentCharFormat(fmt);
}

void WifiBurnDlg::SlotSetProgressValue(unsigned int progress)
{
    if (ui == nullptr) {
        return;
    }
    ui->progressBarReceive->setValue(progress);
}

void WifiBurnDlg::SlotSetProgressRange(int min, int max)
{
    if (ui == nullptr) {
        return;
    }
    ui->progressBarReceive->setRange(min, max);
}

void WifiBurnDlg::changeEvent(QEvent* event)
{
    if (ui == nullptr) {
        return;
    }
    if (lastWinStates == windowState()) {
        QWidget::changeEvent(event);
        return;
    }
    if (windowState() == Qt::WindowMaximized) {
        lastWinStates = windowState();
        ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_NAME, COLUMN_WIDTH_SIZE_300);
        ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_PAHT, COLUMN_WIDTH_SIZE_500);
        ui->tableView->setMinimumHeight(COLUMN_MINIMUM_HEIGHT_SIZE_400);
    } else if (windowState() == Qt::WindowNoState) {
        lastWinStates = windowState();
        ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_NAME, COLUMN_WIDTH_SIZE_100);
        ui->tableView->setColumnWidth(TABLEVIEW_COLUMN_PAHT, COLUMN_WIDTH_SIZE_200);
        ui->tableView->setMinimumHeight(COLUMN_MINIMUM_HEIGHT_SIZE_192);
    }
    QWidget::changeEvent(event);
}

void WifiBurnDlg::SlotUpdateList()
{
    UpdateList();
}

void WifiBurnDlg::SlotActionShow() const
{
    if (burnCtrl == nullptr || burnCtrl->IsBusy() ||
        burnCtrl->GetBurnFsm() == HI_BURN_FSM::FSM_WORK) {
        ActionShowActEnable(false);
    } else {
        ActionShowActEnable(true);
    }
}

void WifiBurnDlg::ActionShowActEnable(bool enable) const
{
    if (comboBoxBurnInterval != nullptr && actEnglish != nullptr && actChinese != nullptr &&
        actSettings != nullptr && actChangeChip != nullptr) {
        comboBoxBurnInterval->setEnabled(enable);
        actSettings->setEnabled(enable);
        actChinese->setEnabled(enable);
        actEnglish->setEnabled(enable);
        actChangeChip->setEnabled(enable);
    }
}

void WifiBurnDlg::SaveSettingCfg() const
{
    int baud;
    int databits;
    int stopbits;
    QSerialPort::Parity parityVal;
    int flowctrl;
    GetComSettingFromGloble(baud, databits, stopbits, parityVal, flowctrl);
    QString fileName = QCoreApplication::applicationDirPath() + "\\configure";
    QSettings cfg(fileName + "\\config_setting.ini", QSettings::IniFormat);
    cfg.setValue(SET_CONFIG + "/" + INI_BAUD, QString::number(baud));
}

void WifiBurnDlg::InitGetSettingCfg() const
{
    if (portType == Base::TCP_PORT) {
        return;
    }
    QString fileName = QCoreApplication::applicationDirPath() + "\\configure";
    QSettings cfg(fileName + "\\config_setting.ini", QSettings::IniFormat);
    int baud = cfg.value(SET_CONFIG + "/" + INI_BAUD).toInt();
    SEBOOT_SHAKE_HANDS_FRAME *head = reinterpret_cast<SEBOOT_SHAKE_HANDS_FRAME *>(Global::shakeHandSignal);
    head->baudRate = baud;
    head->checkSum = ChannelClass::Channel::SopCrc16(static_cast<PBYTE>(Global::shakeHandSignal),
        SHAKE_HAND_SIGNAL_LEN - 2); // crc16 is 2
}

}
